import json
import settings
import pandas as pd
from datetime import datetime, timedelta
from io import BytesIO
import traceback
from common import constants
from common.log import logger

from db.es.es_service import ElasticsearchStorage
from bot.insurance_planner_gpt.interface.base_handler import BaseHandler

es = ElasticsearchStorage()


class FeedbackHandler(BaseHandler):
    def get(self):
        self.set_default_headers()
        text_info = self.get_argument('textInfo', '')
        session_id = self.get_argument('userId', '')
        attitude = self.get_argument('attitude', '')
        bad_option = self.get_argument('badoption', '')
        user_prefer = self.get_argument('userPrefer', '')

        if not session_id or not text_info:
            return "no value"

        query = {
            "query": {
                "bool": {
                    "must": [
                        {
                            "term": {
                                "session_id": {
                                    "value": session_id
                                }
                            }
                        }, {
                            "term": {
                                "text_info.keyword": {
                                    "value": text_info
                                }
                            }
                        }
                    ]
                }
            }
        }
        results = es.search_documents(settings.CONVERSATION_HISTORY_INDEX, query)

        if results:
            # 更新文档
            document_id = results[0]['_id']
            updated_fields = {
                "attitude": attitude,
                'badoption': bad_option,
                'userPrefer': user_prefer
            }
            es.update_document(settings.CONVERSATION_HISTORY_INDEX, document_id, updated_fields)

        self.write("success")


class DownLoadUserSessionConversationHandler(BaseHandler):

    def get(self):
        self.set_default_headers()
        start_date = self.get_argument('start_date', '')
        end_date = self.get_argument('end_date', '')

        try:
            session_ids = set([])
            if not start_date:
                start_date = datetime.now().strftime('%Y-%m-%d')
            if not end_date:
                end_date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
            # 定义查询条件

            date_range_query = {
                "range": {
                    "message_time": {
                        "gte": start_date,
                        "lte": end_date
                    }
                }
            }
            user_session_query = {
                "query": {
                    "bool": {
                        "must": [date_range_query]
                    }
                },
                "size": 1000
            }

            # 执行查询
            session_results = es.search_documents(settings.USER_SESSION_INDEX, user_session_query)

            if session_results:
                # 创建一个空的DataFrame
                df = pd.DataFrame(columns=["用户账号", "对话id", "角色", "对话内容", "对话时间", "态度", "踩的原因", "用户建议", "坐席转发", "渠道类型"])
                # 提取查询结果
                for hit in session_results:
                    session_id = hit["_source"]["session_id"]
                    user_name = hit["_source"]["user_name"]
                    if session_id in session_ids:
                        continue
                    query = {
                        "query": {
                            "bool": {
                                "must": [
                                    {
                                        "term": {
                                            "session_id": {
                                                "value": session_id
                                            }
                                        }
                                    }
                                ]
                            }
                        }, "sort": [
                            {
                                "message_time": {
                                    "order": "asc"
                                }
                            }
                        ]
                        , "size": 1000
                    }
                    results = es.search_documents(settings.CONVERSATION_HISTORY_INDEX, query)
                    if results:
                        # 遍历查询结果
                        for hit in results:
                            session_id = hit["_source"].get("session_id", None)
                            role = hit["_source"].get("role", None)
                            text_info = hit["_source"].get("text_info", None)
                            message_time = hit["_source"]["message_time"]
                            message_id = hit["_source"]["message_id"]
                            attitude = hit["_source"].get("attitude", None)
                            badoption = hit["_source"].get("badoption", None)
                            userPrefer = hit["_source"].get("userPrefer", None)
                            client_type = hit["_source"].get("client_type", 'planner')
                            agent_transfer = "否"
                            if message_id and "agent" in message_id:
                                agent_transfer = "是"

                            df = df.append(
                                {"用户账号": user_name, "对话id": session_id, "角色": role, "对话内容": text_info,
                                 "对话时间": message_time,
                                 "态度": attitude,
                                 "踩的原因": badoption,
                                 "用户建议": userPrefer, "坐席转发": agent_transfer, "渠道类型": client_type},
                                ignore_index=True)
                    session_ids.add(session_id)

                def add_empty_row(group):
                    return pd.concat([group, pd.DataFrame([[''] * len(group.columns)], columns=group.columns)],
                                     ignore_index=True)

                df = df.groupby('用户账号').apply(add_empty_row).reset_index(drop=True)

                excel_io = BytesIO()
                df.to_excel(excel_io, index=False)
                # 将BytesIO的内容发送给客户端作为附件下载
                excel_io.seek(0)  # 将指针回到文件开头，确保从头开始读取

                # 导出到Excel文件
                file_name = f"conversation_{start_date}.xlsx"

                self.set_header("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
                self.set_header("Content-Disposition", "attachment; filename=" + file_name)
                # 将 BytesIO 内容发送给客户端
                self.write(excel_io.getvalue())

            self.write("无数据")
        except Exception:
            logger.error(traceback.format_exc())
            self.write("系统异常,请稍后再试")


class GetConversationHandler(BaseHandler):
    def get(self):
        self.set_default_headers()
        start_date = self.get_argument('start_date', '')
        end_date = self.get_argument('end_date', '')
        text_info = self.get_argument('textInfo', '')
        attitude = self.get_argument('attitude', '')
        data = []
        try:
            session_ids = set([])
            if not start_date:
                start_date = datetime.now().strftime('%Y-%m-%d')
            if not end_date:
                end_date = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
            # 定义查询条件

            date_range_query = {
                "range": {
                    "message_time": {
                        "gte": start_date,
                        "lte": end_date
                    }
                }
            }
            session_query = {
                "query": {
                    "bool": {
                        "must": [date_range_query]
                        # "filter": [text_match_query],
                        # "should": [attitude_query]
                    }
                },
                "size": 1000
            }

            if attitude:
                obj = {
                    "term": {
                        "attitude": {
                            "value": attitude
                        }
                    }
                }
                session_query["query"]["bool"]["must"].append(obj)

            # 构建文字模糊匹配查询条件
            if text_info:
                text_match_query = {
                    "match_phrase": {
                        "text_info": {
                            "query": text_info
                        }
                    }
                }
                session_query["query"]["bool"]["must"].append(text_match_query)

            # 执行查询
            results = es.search_documents(settings.CONVERSATION_HISTORY_INDEX, session_query)

            if results:
                # 提取查询结果
                for hit in results:
                    session_id = hit["_source"]["session_id"]
                    session_ids.add(session_id)
                query = {
                    "query": {
                        "bool": {
                            "must": [
                                {
                                    "terms": {"session_id": list(session_ids)}
                                }
                            ]
                        }
                    }, "sort": [
                        {
                            "session_id": {
                                "order": "asc"
                            }
                        },
                        {
                            "message_time": {
                                "order": "asc"
                            }
                        }
                    ]
                    , "size": 1000
                }
                results = es.search_documents(settings.CONVERSATION_HISTORY_INDEX, query)
                if results:
                    # 遍历查询结果
                    data_dict = {}
                    for hit in results:
                        session_id = hit["_source"].get("session_id", None)
                        role = hit["_source"].get("role", None)
                        text_info = hit["_source"].get("text_info", None)
                        message_time = hit["_source"]["message_time"]
                        attitude = hit["_source"].get("attitude", None)
                        badoption = hit["_source"].get("badoption", None)
                        userPrefer = hit["_source"].get("userPrefer", None)

                        conversation = {
                            "session_id": session_id,
                            "role": role,
                            "text_info": text_info,
                            "message_time": message_time,
                            "attitude": attitude,
                            "badoption": badoption,
                            "userPrefer": userPrefer
                        }
                        if session_id in data_dict:
                            data_dict[session_id]["conversation"].append(conversation)
                        else:
                            data_dict[session_id] = {"session_id": session_id, "conversation": [conversation]}
                    # 将字典转换为列表形式
                    data = list(data_dict.values())
                self.write(json.dumps(data))
            else:
                self.write(json.dumps(data))
        except Exception:
            logger.error(traceback.format_exc())
            self.write(json.dumps(data))


class GetSessionIdByUserHandler(BaseHandler):

    def get(self):
        self.set_default_headers()
        sessionHistory = {}
        sessionIds = []
        try:
            userName = self.get_argument('userName', '')
            sessionHistory['user_name'] = userName
            sessionHistory['client_type'] = 'ydt_h5'

            query = {
                'query': {
                    'match': {
                        'user_name': userName
                    }
                }, "sort": [
                    {
                        "message_time": {
                            "order": "desc"
                        }
                    }
                ]
            }
            results = es.search_documents(settings.USER_SESSION_INDEX, query)
            if results:
                for result in results:
                    sessionDict = {}
                    sessionDict["sessionId"] = result['_source']['session_id']
                    sessionDict["title"] = result['_source']['session_title']
                    sessionDict["createTime"] = result['_source']['message_time']
                    sessionIds.append(sessionDict)

            sessionHistory["session_ids"] = sessionIds

            self.write(json.dumps(sessionHistory))
        except Exception as ee:
            self.write(json.dumps(sessionHistory))


class GetConversationBySessionIdHandler(BaseHandler):

    def get(self):
        self.set_default_headers()
        conversationHistory = {}
        try:
            session_id = self.get_argument('sessionId', '')
            query = {
                "query": {
                    "bool": {
                        "must": [
                            {
                                "term": {
                                    "session_id": {
                                        "value": session_id
                                    }
                                }
                            }
                        ]
                    }
                }, "sort": [
                    {
                        "message_time": {
                            "order": "asc"
                        }
                    }
                ]
                , "size": 1000
            }
            results = es.search_documents(settings.CONVERSATION_HISTORY_INDEX, query)

            messages = []
            conversationHistory['client_type'] = 'ydt_h5'
            conversationHistory["session_id"] = session_id
            conversationHistory["messages"] = messages
            if results:

                delete = []

                for hit in results:
                    try:
                        message_id = hit["_source"]["message_id"]
                        # 展示历史记录的时候只保留坐席修改后的对话
                        if 'agent_' in message_id:
                            delete.append('origin_' + message_id.replace('agent_', ''))
                        msg_type = hit["_source"].get('msg_type', 'text')
                        # 查询历史对话过滤掉方案信息
                        if msg_type and constants.MESSAGE_TYPE_AGENT_SOLUTION == msg_type:
                            continue

                        logger.info('hit:{}'.format(hit))
                        role = hit["_source"]["role"]
                        timestamp = hit["_source"]["message_time"]
                        text_info = hit["_source"]["text_info"]
                        timestamp = datetime.strftime(datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.%f'),
                                                      '%Y-%m-%d %H:%M:%S')

                        content = {}
                        content['role'] = role
                        content['message_id'] = message_id
                        content['timestamp'] = timestamp
                        content['zanShow'] = 'true'
                        content['caiShow'] = 'true'
                        content['content'] = [
                            {
                                "msg_type": msg_type,
                                "data": text_info}
                        ]
                        messages.append(content)

                    except Exception as ee:
                        logger.error(traceback.format_exc())
                        continue

                new_messages = [message for message in conversationHistory["messages"] if
                                message.get('message_id') not in delete]
                conversationHistory["messages"] = new_messages
        except Exception as ee:
            logger.error(traceback.format_exc())

        self.write(json.dumps(conversationHistory))
